package com.qumitech.visualnovel.service.robot.impl;

import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.exception.BusinessException;
import com.qumitech.visualnovel.component.util.GenPhoUtil;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.component.util.ExcelUtil;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.common.ResultEnum;
import com.qumitech.visualnovel.pubdef.constant.SqlConstant;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.service.robot.RobotService;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Auther: jlyin
 * @Date: 2018/12/7 15:01
 * @Description:
 */
@Service
public class RobotServiceImpl implements RobotService {
    private final Logger Log = LoggerFactory.getLogger(this.getClass());

    private static final String ROBOT_ACCOUNT_URL = "/robot";
    private static final String ROBOT_ACCOUNT_ADMIN_URL = "/admin/robot";
    private static final String ROBOT_LIST_URL = "/admin/robot/list";

    @Override
    public BaseRsp getRobotAccount(Long uid) {
        String url = UrlConstant.SERVER_URL + ROBOT_ACCOUNT_ADMIN_URL + '/' + uid;
        String body = HttpInvokeUtil.httpGet(url, null, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()
                || rsp.getData() == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rsp;
    }

    @Override
    public BaseRsp getRobotAccountWithNull(Long uid) {
        String url = UrlConstant.SERVER_URL + ROBOT_ACCOUNT_ADMIN_URL + '/' + uid;
        String body = HttpInvokeUtil.httpGet(url, null, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()
                || rsp.getData() == null) {
            return null;
        }
        return rsp;
    }

    @Override
    public BaseRsp getRobotsByType(Integer type, String subType) {
        String url = UrlConstant.SERVER_URL + ROBOT_ACCOUNT_ADMIN_URL;
        Map<String, String> requestParams = ImmutableMap.of("content_type", subType);
        String body = HttpInvokeUtil.httpGet(url, requestParams, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()
                || rsp.getData() == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rsp;
    }

    @Async
    @Override
    public void importRobot(MultipartFile file) {
        Map<Integer, Map<Integer, Object>> map = new HashMap<>();
        try {
            map = ExcelUtil.readExcelContentz(file);
        } catch (Exception e) {
            Log.error("[importRobot] import excel fail,{}", e);
        }

        String url = UrlConstant.SERVER_URL + ROBOT_ACCOUNT_URL;

        for (Integer key : map.keySet()) {
            Map<Integer, Object> robot = map.get(key);
            try {
                Float f = Float.valueOf(robot.get(0).toString());
                int sex = f.intValue();
                String nickname = (String) robot.get(1);
                String signature = (String) robot.get(2);
                String avatar = (String) robot.get(3);
                Log.info("[------------]key:{}----sex:{}----nickname:{}------signature:{}------avatar:{}", key, sex, nickname, signature, avatar);

                Map<String, String> requestParams = new HashMap<>();
                requestParams.put("phone", GenPhoUtil.getRobotTel());
                requestParams.put("nickname", nickname);
                requestParams.put("avatar",avatar);
                requestParams.put("sex", String.valueOf(sex));
                requestParams.put("signature", signature);
                requestParams.put("birthday", "2000-1-1");
                Log.info("[importRobot] request, url:{}, param:{}", url, requestParams);
                String body = HttpInvokeUtil.httpPostJson(url, requestParams, UrlConstant.DefaultEncode);
                Log.info("[importRobot] response :{}", body);
                BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
                if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
                    throw new BusinessException(ResultEnum.FAILURE);
                }
            } catch (Exception e) {
                Log.error("[importRobot] add Robot fail. name:{}, error:{}", robot, e);
            }
        }
    }

    @Override
    public BaseRsp getRobotList(Integer offset, Integer limit, String sex) {
        String url = UrlConstant.SERVER_URL + ROBOT_LIST_URL;
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("offset", offset.toString());
        paramMap.put("limit", limit.toString());
        if(sex != null){
            paramMap.put("sex", sex);
        }
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rsp;
    }

    @Override
    public BaseRsp getRandomRobot(String sex) {
        BaseRsp baseRsp = getRobotList(SqlConstant.DEFAULT_OFFSET, SqlConstant.DEFAULT_LIMIT, sex);
        Integer count;
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(baseRsp.getData()));
            count = (Integer) jsonObject.get("count");
        }catch (Exception e){
            return null;
        }
        if(count == 0){
            return null;
        }
        Integer limit = SqlConstant.DEFAULT_LIMIT;
        Integer offset = new Random().nextInt(count);
        return getRobotList(offset, limit, sex);
    }
}
